const fs = require('fs')
const path = require('path')
const { initNewAnswer } = require('./answers-raw-data')
const root = path.join(__dirname, '../survey-data/surveys-raw-data')

function getSurvey(id) {
    try {
        const survey = fs.readFileSync(
            path.join(root, `${id}.survey.json`),
            'utf8'
        )
        return JSON.parse(survey)
    } catch (error) {
        throw error
    }
}

function addSurvey(survey) {
    try {
        fs.writeFileSync(
            path.join(root, `${survey.id}.survey.json`),
            JSON.stringify(survey),
            { mode: 0o444 }
        )
        initNewAnswer(survey.id)
    } catch (error) {
        throw error
    }
}

function countSurvey() {
    try {
        const files = fs.readdirSync(root)
        return files.length
    } catch (error) {
        throw error
    }
}

module.exports = {
    countSurvey,
    addSurvey,
    getSurvey,
}
